import { login } from '@/api/mes-web/login-for-keyparts'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken(),
  keypartsname: '',
  ulocNo: ''

}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_KEYPARTSNAME: (state, keypartsname) => {
    state.keypartsname = keypartsname
  },
  SET_ULOCNO: (state, ulocNo) => {
    state.ulocNo = ulocNo
  }
}

const actions = {
  // login for keyparts
  login({ commit }, userInfo) {
    const { username, password, ulocNo } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password, ulocNo: ulocNo }).then(response => {
        // console.log(response)
        if (response.code === 200) {
          commit('SET_TOKEN', 'login-for-keyparts')
          setToken('login-for-keyparts')
          commit('SET_KEYPARTSNAME', username)
          commit('SET_ULOCNO', ulocNo)
          resolve()
        } else {
          reject()
        } 
      }).catch(error => {
        reject(error)
      })
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
